<?php

namespace App\Http\Controllers\OperationManagement;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\OperationManagement\TrashSite;
use Illuminate\Database\QueryException;
use App\Http\Requests\OperationManagement\TrashSiteRequest;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

/**
 * @group 基础信息管理->环卫->垃圾点位
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */

class TrashSiteController extends Controller
{
    /**
     * 垃圾点位查看列表
     *
     * @bodyParam name string require 垃圾点位
     * @bodyParam type char require 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     *
     * @queryParam mark string 编号
     * @queryParam name string 垃圾点位
     * @queryParam address string 详细地址
     * @queryParam location string 经纬度-点 115.24556 25.14551
     * @queryParam company string 所属公司
     * @queryParam type char 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     * @queryParam mold char 容器类型 1果皮箱 2箱体 3桶
     * @queryParam number int 总数量
     * @queryParam bulk float 总容积
     * @queryParam clean_num int 日清运次数
     * @queryParam path int 路线
     * @queryParam clean_time string 清运时间范围
     * @queryParam bulk_avg int 日均垃圾容量
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $trashSite = new TrashSite;
        $data = $trashSite->getList($request);
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 新增垃圾点位
     *
     * @bodyParam name string require 垃圾点位
     * @bodyParam address string require 详细地址
     * @bodyParam location string 经纬度-点 115.24556 25.14551
     * @bodyParam company string 所属公司
     * @bodyParam type char require 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     * @bodyParam mold char require 容器类型 1果皮箱 2箱体 3桶
     * @bodyParam bulk float require 总容积
     * @bodyParam clean_num int require 日清运次数
     * @bodyParam path int require 路线
     * @bodyParam clean_time string require 清运时间范围
     * @bodyParam bulk_avg int require 日均垃圾容量
     *
     * @queryParam mark string 编号
     * @queryParam name string 垃圾点位
     * @queryParam address string 详细地址
     * @queryParam location string 经纬度-点 115.24556 25.14551
     * @queryParam company string 所属公司
     * @queryParam type char 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     * @queryParam mold char 容器类型 1果皮箱 2箱体 3桶
     * @queryParam number int 总数量
     * @queryParam bulk float 总容积
     * @queryParam clean_num int 日清运次数
     * @queryParam path int 路线
     * @queryParam clean_time string 清运时间范围
     * @queryParam bulk_avg int 日均垃圾容量
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            $data = $request->all();
            // $data['location'] = \DB::raw("GeomFromText('Point({$request->input('location')})')");
            $location = $request->input('location','');
            if(!empty($location)){
                $data['location'] = Point::fromString($location);
            }
            $mark = TrashSite::orderBy('mark','desc')->value('mark');
            if(is_null($mark)){
                $data['mark'] = 1;
            }else{
                $data['mark'] = seriesNum($mark);
            }
            $data = TrashSite::create($data);
            return response()->json(encodeMsg($data,201));
        } catch (QueryException $e) {
            dd($e);
            return response()->json(encodeMsg(['message' => '垃圾站点添加失败!'],400));
        }
    }

    /**
     * 查看垃圾点位
     *
     * @bodyParam id int require 垃圾点位id
     *
     * @queryParam mark string 编号
     * @queryParam name string 垃圾点位
     * @queryParam address string 详细地址
     * @queryParam location string 经纬度-点 115.24556 25.14551
     * @queryParam company string 所属公司
     * @queryParam type char 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     * @queryParam mold char 容器类型 1果皮箱 2箱体 3桶
     * @queryParam number int 总数量
     * @queryParam bulk float 总容积
     * @queryParam clean_num int 日清运次数
     * @queryParam path int 路线
     * @queryParam clean_time string 清运时间范围
     * @queryParam bulk_avg int 日均垃圾容量
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = TrashSite::find($id);
        if($data == []) {
            return response()->json(encodeMsg(["message" => "没有该垃圾站点信息!"], 404));
        } else {
            return response()->json(encodeMsg($data,200));
        }
    }

    /**
     * 修改垃圾点位
     *
     * @bodyParam id int require 垃圾点位id
     * @bodyParam name string require 垃圾点位
     * @bodyParam address string require 详细地址
     * @bodyParam location string 经纬度-点 115.24556 25.14551
     * @bodyParam company string 所属公司
     * @bodyParam type char require 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     * @bodyParam mold char require 容器类型 1果皮箱 2箱体 3桶
     * @bodyParam bulk float require 总容积
     * @bodyParam clean_num int require 日清运次数
     * @bodyParam path int require 路线
     * @bodyParam clean_time string require 清运时间范围
     * @bodyParam bulk_avg int require 日均垃圾容量
     *
     * @queryParam mark string 编号
     * @queryParam name string 垃圾点位
     * @queryParam address string 详细地址
     * @queryParam location string 经纬度-点 115.24556 25.14551
     * @queryParam company string 所属公司
     * @queryParam type char 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     * @queryParam mold char 容器类型 1果皮箱 2箱体 3桶
     * @queryParam number int 总数量
     * @queryParam bulk float 总容积
     * @queryParam clean_num int 日清运次数
     * @queryParam path int 路线
     * @queryParam clean_time string 清运时间范围
     * @queryParam bulk_avg int 日均垃圾容量
     *
     * @return \Illuminate\Http\Response
     */
    public function update(TrashSiteRequest $request, $id)
    {
        $trashSite = TrashSite::find($id);
        if($trashSite == []) {
            return response()->json(encodeMsg(["message" => "没有该垃圾站点信息!"], 404));
        }
        try {
            $data = $request->all();
            $location = $request->input('location','');
            if(!empty($location)){
                $data['location'] = Point::fromString($location);
            }
            $trashSite->update($data);
            return response()->json(encodeMsg($trashSite,200));
        } catch (QueryException $e) {
            return response()->json(encodeMsg(['message' => '垃圾站点修改失败!'],400));
        }
    }

    /**
     * 删除垃圾站点
     *
     *
     * @bodyParam id int required  垃圾点位id
     * @response 204 {
     *   "message": "垃圾站点删除成功"
     * }
     *
     *
     * @response 404 {
     *  "message": "没有该垃圾站点信息"
     * }
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $trashSite = TrashSite::find($id);
        if($trashSite == []) {
            return response()->json(encodeMsg(["message" => "没有该垃圾站点信息!"], 404));
        }
        if($trashSite->delete()) {
            return response()->json(encodeMsg(["message" => "垃圾站点删除成功!"], 204));
        } else {
            return response()->json(encodeMsg(["message" => "垃圾站点删除失败"], 400));
        }
    }

    /**
     * 批量删除垃圾站点
     *
     * @bodyParam  ids int required  id集合字符串[格式：ids=1,2,3]
     * @response 204 {
     *   "message": "垃圾站点删除成功"
     * }
     *
     *
     */
    public function delete($ids)
    {
        $listId = explode(',', $ids);
        TrashSite::whereIn('id',$listId)->delete();
        return response()->json(encodeMsg(["message" => "垃圾站点删除成功!"], 204));
    }

    /**
     * 垃圾点位信息导出
     * @queryParam id 序号
     * @queryParam name 垃圾点位
     * @queryParam address 详细地址
     * @queryParam location 经纬度
     * @queryParam company 所属公司
     * @queryParam type|status:1=>有害垃圾,2=>可回收垃圾,3=>干垃圾,4=>湿垃圾 垃圾类型
     * @queryParam mold|status:1=>果皮箱,2=>垃圾箱,3=>垃圾桶 容器类型
     * @queryParam number 总数量
     * @queryParam bulk 总容积
     * @queryParam clean_num 日清运次数
     * @queryParam path 路线
     * @queryParam clean_time 清运时间范围
     * @queryParam bulk_avg 日均垃圾容量
     *
     *
     */
    public function export(Request $request)
    {
        $request['per_page'] = 9999;
        $cellData = $this->index($request);//excel的内容
        $data = $cellData->getData()->data->data;
        foreach ($data as $key => $val) {
            if(!empty($val->location)){
                $val->location = implode(' ',$val->location->coordinates);
            }
        }
        $writer = excelExport($data,genExport());
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="垃圾点位信息.xlsx"');//execl名字
        $writer->save('php://output');
    }

    /**
     * 垃圾点位导入 excel
     *
     * @queryParam name string 垃圾点位
     * @queryParam address string 详细地址
     * @queryParam location string 经纬度-点 115.24556 25.14551
     * @queryParam company string 所属公司
     * @queryParam type char 垃圾类型 1可回收垃圾 2有害垃圾 3厨余垃圾 4其他垃圾
     * @queryParam mold char 容器类型 1果皮箱 2箱体 3桶
     * @queryParam number int 总数量
     * @queryParam bulk float 总容积
     * @queryParam clean_num int 日清运次数
     * @queryParam path int 路线
     * @queryParam clean_time string 清运时间范围
     * @queryParam bulk_avg int 日均垃圾容量
     *
     * @return \Illuminate\Http\Response
     */
    public function import(Request $request)
    {
        $data = excelImport($request);
        $trashSite = [];
        if(!empty($data)){
            foreach ($data as $k => $v) {
                unset($v[0]);
                foreach ($v as $key => $row) {
                    DB::beginTransaction();
                    try {
                        $trashSite[$k][$key]['name'] = $row[0];
                        $trashSite[$k][$key]['address'] = $row[1];
                        if (!empty($row[2])) {
                            $trashSite[$k][$key]['location'] = Point::fromString($row[2]);
                        }
                        switch ($row[3]) {
                            case '可回收垃圾':
                                $trashSite[$k][$key]['type'] = 1;
                                break;
                            case '有害垃圾':
                                $trashSite[$k][$key]['type'] = 2;
                                break;
                            case '厨余垃圾':
                                $trashSite[$k][$key]['type'] = 3;
                                break;
                            case '其他垃圾':
                                $trashSite[$k][$key]['type'] = 4;
                                break;
                            default:
                                break;
                        }
                        switch ($row[4]) {
                            case '果皮箱':
                                $trashSite[$k][$key]['mold'] = 1;
                                break;
                            case '垃圾箱':
                                $trashSite[$k][$key]['mold'] = 2;
                                break;
                            case '垃圾桶':
                                $trashSite[$k][$key]['mold'] = 3;
                                break;
                            default:
                                break;
                        }
                        $trashSite[$k][$key]['number'] = $row[5];
                        $trashSite[$k][$key]['bulk'] = $row[6];
                        $trashSite[$k][$key]['clean_num'] = $row[7];
                        $trashSite[$k][$key]['path'] = $row[8];
                        $trashSite[$k][$key]['clean_time'] = $row[9];
                        $trashSite[$k][$key]['bulk_avg'] = $row[10];
                        $data = $trashSite[$k][$key];
                        $res = TrashSite::where(function($query) use ($data){
                            if(!empty($data['location'])){
                                $query->distance('location',$data['location'],10);
                            }
                            unset($data['location']);
                            $query->where($data);
                        })->first();
                        if (empty($res)) {
                            TrashSite::create($trashSite[$k][$key]);
                        }
                        DB::commit();
                    } catch (QueryException $e) {
                        DB::rollBack();
                        dd($e);
                        return response()->json(encodeMsg(['message' => '导入失败!'],400));
                    }
                }
                unset($trashSite[$k][$key]);
            }
            unset($trashSite[$k]);
        }
        if(Storage::disk('public')->exists('uploads/'.$request->file('file')->getClientOriginalName())) {
            return response()->json(encodeMsg(['message' => '文件已上传!'],200));
        }
    }

}
